import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/users/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate.vue'
import GoodsList from '../components/goods/List.vue'
import Order from '../components/order/Order.vue'
import Params from '../components/goods/Params.vue'
import Report from '../components/report/Report.vue'
import Add from '../components/goods/Add.vue'
Vue.use(VueRouter)
    // 暴露路由对象
const router = new VueRouter({
        routes: [{
                path: '/',
                redirect: '/login' // 路由重定向
            },
            {
                path: '/login',
                component: Login
            },
            {
                path: '/home',
                component: Home,
                redirect: '/welcome',
                children: [
                    { path: '/welcome', component: Welcome },
                    { path: '/users', component: Users },
                    { path: '/rights', component: Rights },
                    { path: '/roles', component: Roles },
                    { path: '/categories', component: Cate },
                    { path: '/goods', component: GoodsList },
                    { path: '/goods/add', component: Add },
                    { path: '/orders', component: Order },
                    { path: '/params', component: Params },
                    { path: '/reports', component: Report }
                ]
            }
        ]
    })
    // 如果用户没有登录，但是直接通过URL访问特定页面，需要重新导航到登录页面
    // 挂载路由导航守卫：控制访问权限
router.beforeEach((to, from, next) => {
    // to 将要访问的路径
    // from 代表从哪个路径跳转而来
    // next 是一个函数，表示放行
    // next() 放行 next('/login') 强制跳转
    if (to.path === '/login') return next() //访问是登陆页不具有权限的页面，就直接放行
        // 但如果是访问有权限的页面呢   
        // 1. 获取token
    const tokenstr = window.sessionStorage.getItem('token')
    if (!tokenstr) return next('/login') // 2.token不存在，强制跳转
    next() // 3.token存在，直接放行
})

export default router